<template>
  <view class="order-content">
    <u-navbar bgColor="#fff" :safeAreaInsetTop="true" :placeholder="true" :height="60">
      <view slot="left"></view>
      <view slot="center" class="search-box">
        <view class="inner-i">
          <view style="height: 30rpx"></view>
          <u-search
            v-model="searchValue"
            placeholder="搜索素材名称"
            bgColor="#f3f3f3"
            @search="getData"
            :showAction="false"
          ></u-search>
        </view>
        <view class="title-area">
          <view class="title">
            <image
              class="sc-icon"
              style="width: 37rpx; height: 37rpx"
              src="@/static/image/sc.png"
            ></image>
            我的作品
          </view>
          <view class="right">
            <u-icon
              color="#fc7110"
              size="20px"
              name="plus-circle-fill"
              @click="show = true"
            ></u-icon>
          </view>
        </view>
      </view>
    </u-navbar>
    <view class="content-box" v-if="dataList && dataList.length">
      <view class="sc-list" v-for="(item, index) in dataList" :key="index">
        <view class="left">
          <view class="name">{{ item.articleTitle }}</view>
          <view class="sub">
            <view style="line-height: 22px">
              {{ item.articleContent }}
            </view>
            <view v-if="item.articleType == '1'" style="margin-top: 20rpx">
              <Cvideo :url="item.articleAttaUrl" @play="tapNav(item)" />
            </view>
            <view v-if="item.articleType == '2'" style="margin-top: 20rpx">
              <sy-audio
                isCountDown
                ref="audio"
                :src="item.articleAttaUrl"
                audioCover=""
                subheading=""
                :audioTitle="item.articleTitle"
                @nav="() => handleNav(item)"
              ></sy-audio>
            </view>
          </view>
          <view class="ab">
            <view class="li">
              <u-icon name="account" color="#909090"></u-icon>
              {{ item.userName }}
            </view>
            <view class="li">
              {{ item.upvoteCount || 0 }}
              赞
            </view>
            <view class="li">
              {{ item.commentCounts || 0 }}
              评论
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-loadmore :status="loadStatus" @loadmore="getList('more')" />
    <u-action-sheet
      :actions="actionsList"
      :show="show"
      @select="selectClick"
      @close="show = false"
      closeOnClickOverlay
    ></u-action-sheet>
    <u-toast ref="uToast"></u-toast>
    <GcmRedBag
      ref="GcmRedBagRef"
      :money="getMoney"
      :options="redBagConfig"
      @onConfirm="onConfirm"
    />
    <cm-devtool />
	<GModal :value="showModal" title="活动须知" buttonText="接受" :content="content" @cancel="showModal=false" @confirm="acceptLawFun" />
  </view>
</template>

<script>
import { articleList, articleGetRed, articleGet } from '@/api/yuedu'
import GcmRedBag from '@/components/gcm-red-bag/gcm-red-bag'
import Cvideo from '@/components/c-video'
import ZAudio from '@/components/uniapp-zaudio'
import { acceptLaw } from '@/api/user'
import GModal from '@/components/ithui-bullet/ithui-bullet-two.vue'
export default {
  components: {
	GModal,
    GcmRedBag,
    Cvideo
  },
  data() {
    return {
		showModal: false,
		content: `
			<div>（一）合法性原则：上传资料必须符合国家法律法规，不得侵犯他人合法权益，不得传播违法信息，不得包含庸俗、暴力、消极等内容。</div>
			<div>（二）真实性原则：上传资料应当真实可靠，不得虚构、篡改、误导。 </div>
			<div>（三）合规性原则：上传资料应符合平台相关管理规定，不得违反平台政策，符合相关标准，不得有损平台形象。</div>
			<div>（四）材料类型：包括文本、图片、音视频等，不得涉及国家机密、侵犯他人合法权益、传播违法信息。提交材料内容必须是科幻文学类作品或者讲述科幻阅读心得体会。</div>
			<div>（五）质量要求：上传资料应具有较高的质量，视频/音频时长大于等于2分钟，小于等于5分钟。拍摄画面清晰，镜头运用流畅、结构完整、画质清晰，视频大小不超过500MB。音频必须吐字清晰，每天可打卡多次，只计为1次。</div></div>
			<div>（六）违规制度：平台管理员定期对上传内容进行审核，有权对不合规等打卡内容进行删除，删除后不计入打卡评审内容。</div>
			<div>（七）奖励制度：每日参加打卡者，在上传作品以后均有机会获取打卡小红包，但每天只能获取1次。连续打卡10次可获取打卡中红包，连续打卡25次可获取打卡大红包。</div>
			<div>（八）评优制度：组织方会在连续打卡25天阅读参与者中，选取作品完成度高，视频拍摄精美者，综合评定10人，奖励价值200元读书卡一张，前20名可以免费参加暑期科普研学班。</div>
			<div>（九）提现制度：打卡者账户里的可申请提现到微信零钱，每天最多提现1次。每次提现金额不少于0.1元，请合理规划提现金额。</div>`,
	  loadStatus: 'nomore',
      redBagConfig: {
        btnText: '开心收下'
      },
      searchValue: null,
      show: false,
      actionsList: [
        {
          name: '自由朗读',
          key: 0
        },
        {
          name: '分享文章',
          key: 1
        },
        {
          name: '上传视频',
          key: 2
        }
      ],
      myData: [],
      dataList: [],
      tabsData: [
        {
          name: '推荐'
        },
        {
          name: '热门'
        },
        {
          name: '原创'
        }
      ],
      getMoney: 0,
      pageSize: 20,
      pageNum: 1
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
    isLogin() {
      return this.$store.getters.token
    }
  },
  onLoad(option) {
    uni.$on('getRedCard', (data) => {
      this.articleGetRedFun(data)
      this.getData()
    })
    if (this.isLogin) {
      this.getData()
    }
  },
  onShow() {
    // if (!this.isLogin) {
    //   setTimeout(() => {
    //     uni.navigateTo({
    //       url: '/pagesSub/userCenter/register'
    //     })
    //   }, 500)
    // }
  },
  onPullDownRefresh() {
    if (this.isLogin) {
      this.getData()
    }
    uni.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.loadStatus !== 'nomore') {
      this.getData('more')
    }
  },
  methods: {
    handleNav(item) {
      let zaudio = new ZAudio({
        continuePlay: false, //续播
        autoPlay: true //自动播放 部分浏览器不支持
      })
      var data = [
        {
          src: item.articleAttaUrl,
          title: item.articleTitle,
          singer: item.userName,
          coverImgUrl: item.avatarUrl
        }
      ]
      zaudio.setAudio(data) //添加音频
      zaudio.setRender(0) //渲染第一首音频
      // uni.navigateTo({
      //   url: `/pagesSub/play/audio?id=${item.articleId}`
      // })
    },
	acceptLawFun() {
	  this.showModal = false
	  acceptLaw().then((res) => {
        if (res.code === 200) {
          this.$store.dispatch('getUserInfoIsLogin')
        }
      })
	},
    articleGetRedFun(data) {
      articleGetRed({
        userId: this.$store.getters.userInfo.userId,
        articleId: data
      }).then((res) => {
        if (res.code === 200) {
          this.getMoney = res.data
          setTimeout(() => {
            this.$refs.GcmRedBagRef.showRedBag()
          }, 1000)
        }
      })
    },
    getData(type) {
      if (type == 'more') {
        this.pageNum++
      } else {
        this.pageNum = 1
        this.dataList = []
      }
      this.loadStatus = 'loading'
      const query = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        status: '0',
        userId: this.$store.getters.userInfo.userId
      }
      if (this.searchValue) {
        query.articleTitle = this.searchValue
      }
      articleList(query).then((res) => {
        if (res.code === 200) {
          this.dataList = this.dataList.concat(res.rows || [])
          if (this.dataList.length >= res.total) {
            this.loadStatus = 'nomore'
          } else {
            this.loadStatus = 'loadmore'
          }
        }
      })
    },
    tapNav(item) {
      uni.navigateTo({
        url: `/pagesSub/play/index?id=${item.articleId}`
      })
    },
    selectClick(row) {
      if (!this.isLogin) {
        this.$refs.uToast.show({
          type: 'default',
          message: '请先注册！',
          duration: 2000,
          complete: () => {
            uni.navigateTo({
              url: '/pagesSub/userCenter/register'
            })
          }
        })
        return
      }
	  if (!this.userInfo.acceptTime) {
	    this.showModal = true
		return
	  }
      this.show = false
      if (row.key === 0) {
        uni.navigateTo({
          url: `/pagesSub/du/index`
        })
      } else if (row.key === 1) {
        uni.navigateTo({
          url: `/pagesSub/du/article`
        })
      } else if (row.key === 2) {
        this.$refs.uToast.show({
          message: '加载中',
          type: 'loading',
          duration: 30000
        })
        uni.chooseVideo({
          sourceType: ['album'], // 从相册选择
          compressed: false,
          success: (res) => {
            // 跳转至B页面并传递临时路径
            if (res.duration >= 120 && res.duration <= 300) {
              this.$refs.uToast.hide()
              uni.navigateTo({
                url: `/pagesSub/du/preVideo?videoPath=${encodeURIComponent(res.tempFilePath)}`
              })
            } else {
              setTimeout(() => {
                this.$refs.uToast.show({
                  type: 'default',
                  message: '视频长度不符，请保持在2-5分钟',
                  duration: 3000
                })
              }, 1000)
            }
          },
          fail: (err) => {
            this.$refs.uToast.hide()
            console.error('选择视频失败:', err)
          }
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.order-content {
  padding-top: 40rpx;
  padding-bottom: 10rpx;
}
.search-box {
  padding: 20rpx;
  background-color: #fff;
  width: 100%;
  .inner-i {
    padding-right: 30%;
  }
}
.sc-icon {
  margin-right: 20rpx;
}
.title-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding-top: 20rpx;
  .title {
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;
  }
}
.title-area-2 {
  .title {
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;
  }
  .flex {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      display: flex;
      align-items: center;
    }
    .right {
      font-size: 12px;
      font-weight: normal;
      color: #666;
    }
  }
  .content-list {
    display: flex;
    padding-top: 20rpx;
    .dl {
      display: inline-block;
      width: 200rpx;
      text-align: center;
    }
    .img {
      width: 180rpx;
      height: 180rpx;
      border: 1px #ccc solid;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .playIcon {
        position: absolute;
        left: 200;
        right: 50%;
        display: none;
      }
    }
    .name {
      margin-top: 10rpx;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 隐藏溢出内容 */
      text-overflow: ellipsis; /* 显示省略号 */
    }
  }
}
.content-box {
  background-color: #ffffff;
  margin: 10rpx 20rpx;
  border-radius: 15rpx;
  padding: 20rpx;
}
.sc-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px #f3f3f3 solid;
  padding: 30rpx 0;
  .left {
    width: 100%;
    .name {
      font-size: 16px;
    }
    .sub {
      font-size: 13px;
      color: #666;
      margin-top: 20rpx;
    }
    .ab {
      display: flex;
      color: #909090;
      font-size: 13px;
      margin-top: 20rpx;
      .li {
        margin-right: 30rpx;
        display: flex;
      }
    }
  }
}
.scroll-view_H {
  white-space: nowrap;
  width: 100%;
}
</style>
